var height = $(document.body).height()+"px";
var rightData = [];
var typeData = [];
//用react封装
var currentpage = 1,totlepage = 1,i;//分页的当前页和总的页数
//表单数据
var tableData = [];
//表单的最高高度、当前第几页、总页数、总行数
var otherData = {maxHeight:'0px',currentpage:0,totlepage:0,totlerows:0,pageLeft:0,pageRight:0};
//分页
var Page = React.createClass({
    setPage: function (e) {
        setPage($(e.target).html());
        this.props.onPageClick(1);
    },
    showPage: function () {
        showPage();
    },
    render: function () {
        {
            var items = [],
                svar = this;
            if(totlepage == 0){
                items.push({num:1,checked:true})
            }else if(totlepage < 6){
                for(i = 1;i <= totlepage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totlepage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totlepage-1;i <= totlepage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }
        }
        return (
            <div className="tableInfo-page">
                <div className="page-number">每页<span className="page-number-list" onClick={this.showPage}>{pagecount}</span>条</div>
                <div className="page-list" style={{top:pageListTop+"px"}}>
                    <ul >
                        {
                            pageList.map(function (item) {
                                return (<li onClick={svar.setPage}>{item}</li>)
                            })
                        }
                    </ul>
                </div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <ol className="page-limit-ol">
                            <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)} ><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                            {
                                items.map(function (item) {
                                    return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)}  className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                                })
                            }
                            <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)} ><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                        </ol>
                    </ol>
                </div>
            </div>
        );
    }
});
//表单组件
var Table = React.createClass({
    render: function () {
        return (
            <tr>
                <td style={{width: '6%'}}>{parseInt(this.props.listNumber)+1}</td>
                <td style={{width: '12%'}}>{this.props.queryresultcode}</td>
                <td style={{width: '12%'}}>{this.props.queryresultname}</td>
                <td style={{width: '15%'}}>{this.props.queryresulttypeName}</td>
                <td style={{width: '15%'}}>{this.props.queryresultstatus==null?"":(this.props.queryresultstatus=="1"?"正常":"已删除")}</td>
                <td style={{width: '20%'}}>{this.props.queryresultremark}</td>
                <td style={{width: '20%'}}>
                    {("1"==this.props.queryresultstatus )?<div className="trButton" onClick={this.props.onClickUpdateShow}>修改</div>:""}
                </td>
            </tr>
        );
    }
});
//权限组件
var Author = React.createClass({
    render: function () {
        return (
            <div className="roleParent">
                <span title={this.props.name} className="roleStyle" data-value={this.props.id} >
                    <input type="checkbox" id={this.props.id} className="rightId_box roleParent-box" data-value={this.props.id} />
                    <span className="roleParent-val" data-value={this.props.id}>{this.props.name}</span>
                </span>
                <div className="roleChild">
                    {
                        this.props.child.map(function (data) {
                            return(
                                <span title={data.name} className={"roleStyle "+data.parentId} data-parentId={data.parentId} data-value={data.id} >
                                    <input type="checkbox" className="rightId_box roleChild-box" data-parentId={data.parentId} data-value={data.id} />
                                    <span>{data.name}</span>
                                </span>
                            )
                        })
                    }
                </div>
            </div>
        );
    }
});
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData:this.props.otherData,
            tableData:this.props.tableData,
            typeData:this.props.typeData,
            rightData:this.props.rightData
        }
    },
    componentDidMount: function () {
        var svar = this;
        suixun.ajax(serverUrl+'/roleManager/listRole.json?param={num:'+pagecount+'}','',"get",function(data){
            if(data.code == 200){
                for(var i=0;i<data.info.list.length;i++){
                    var obj=data.info.list[i];
                    tableData[i] = {queryresultid:obj.id,queryresultcode:obj.code,queryresultname:obj.name,queryresultremark:obj.remark,queryresulttype:obj.type,queryresultstatus:obj.status,queryresulttypeName:obj.typeName};
                }
                var pageRight = 0;
                if(data.totalpage > 1){
                    pageRight = 1
                }
                otherData = {maxHeight:height,currentpage:1,totlepage:(data.info.totalpage),totlerows:data.info.totalNum,pageLeft:0,pageRight:pageRight};
                currentpage = 1;totlepage = data.info.totalpage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData,rightData:rightData});
            }
        });
        //查询角色类型
        suixun.ajax(serverUrl+'/roleManager/listRoleTypeByIdName.json','',"get",function(data){
            if(data.code == 200){
                for(var i=0;i<data.info.length;i++){
                    var obj=data.info[i];
                    typeData[i] = {id:obj.id,name:obj.name};
                }
                svar.setState({typeData:typeData});
            }
        });
        //查询角色类型
        suixun.ajax(serverUrl+'/roleManager/getMenu.json','',"get",function(data){
            setTimeout(function () {
                suixun.hideLoding();//隐藏加载中
            },500);
            var count = 0;
            if(data.code == 200){
                for(var i=0;i<data.info.length;i++){
                    var obj=data.info[i];
                    if(obj.icon != "" && obj.icon != null){
                        rightData[count] = {id:obj.id,name:obj.name,child:[]};
                        for(var j=0;j<data.info.length;j++){
                            var childObj=data.info[j];
                            if(obj.id == childObj.parentId){
                                rightData[count].child.push({id:childObj.id,name:childObj.name,parentId:childObj.parentId});
                            }
                        }
                        count ++;
                    }
                }
                svar.setState({rightData:rightData});
            }
        });

    },
    /**
     * 分页
     * @param num
     */
    onPageClick: function (num) {
        //分页-调用ajac然后把数据查询出来:获取name的值
        //计算currentpage
        suixun.showLoding();//显示加载中
        var onPageLeft = 0,onPageRight = 1,svar = this;
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totlepage){
            currentpage ++;
        }
        //修改左右的按钮
        if((currentpage == totlepage && totlepage == 1)|| totlepage == 0){
            onPageLeft = 0;
            onPageRight = 0;
        }else if(currentpage == totlepage && totlepage > 1){
            onPageLeft = 1;
            onPageRight = 0;
        }else if(1 < currentpage && currentpage < totlepage){
            onPageLeft = 1;
            onPageRight = 1;
        }
        //执行ajax获取数据然后组装
        var param="param={index:"+currentpage+",num:"+pagecount+"}";
        tableData = [];
        suixun.ajax(serverUrl+'/roleManager/listRole.json',param,"get",function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                for(var i=0;i<data.info.list.length;i++){
                    var obj=data.info.list[i];
                    tableData[i] = {queryresultid:obj.id,queryresultcode:obj.code,queryresultname:obj.name,queryresultremark:obj.remark,queryresulttype:obj.type,queryresultstatus:obj.status,queryresulttypeName:obj.typeName};
                }
                if(data.info.totalpage > 1 && data.info.totalpage > currentpage){
                    onPageRight = 1;
                }else{
                    onPageRight = 0;
                }
                totlepage = data.info.totalpage;
                otherData = {maxHeight:height,currentpage:currentpage,totlepage:(data.info.totalpage),totlerows:data.info.totalNum,pageLeft:onPageLeft,pageRight:onPageRight};
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });

    },
    /**
     * 点击table修改按钮
     */
    onClockUpdate: function () {
        var id=$("#id").val(),code=$("#code").val(),name=$("#name").val(),remark=$("#remark").val(),type=$("#type").val(),svar = this;

        if(type == null){
            suixun.alert("请选择角色类型");
            return;
        }
        if(name == ""){
            suixun.alert("角色名称不能为空!");
            $(".userName-error").show();
            return;
        }
        if(code == ""){
            suixun.alert("角色代码不能为空!");
            $(".userId-error").show();
            return;
        }
        if(remark == ""){
            suixun.alert("备注不能为空!");
            $(".remark-error").show();
            return;
        }
        suixun.showLoding();//显示加载中
        var rightIdList="";
        $(".rightId_box").each(function(i,box) {
            if(box!=null && box.checked)
                rightIdList+=$(box).attr("data-value")+"|";
        });
        if(rightIdList.length>1)
            rightIdList=rightIdList.substring(0,rightIdList.length-1);

        var param="param={";
        param = getJsonDataNotEmpty(param,"id",$("#id").val());
        param = getJsonDataNotEmpty(param,"code",$("#code").val());
        param = getJsonDataNotEmpty(param,"name",$("#name").val());
        param = getJsonDataNotEmpty(param,"remark",$("#remark").val());
        param = getJsonDataNotEmpty(param,"type",$("#type").val());
        param = getJsonDataNotEmpty(param,"nodes",rightIdList);
        param += "}";

        var urls=serverUrl+'/roleManager/saveRole.json';
        if(id!=null && id!=""){
            urls=serverUrl+'/roleManager/updateRole.json';
        }
        suixun.ajax(urls,param,"get",function(data){
            suixun.hideLoding(200);//隐藏加载中
            if(data!=null && data.info == 200){
                suixun.alert("保存成功",function (data) {
                    if(data){
                        svar.onClickHidePop();
                        svar.onPageClick(currentpage);
                    }
                });
            } else {
                suixun.alert("保存失败");
            }
        });
    },
    /**
     * 显示修改界面
     * @param info
     */
    onClickUpdateShow: function (info) {
        suixun.showLoding();//
        $("#id").val(info[0]);//
        $("#name").val(info[1]);//
        $("#remark").val(info[2]);//
        $("#code").val(info[3]);//
        $("#type").val(info[4]);//
        $(".rightId_box").attr("checked",false);
        $(".table-form-title").html("修改角色信息");
        var param="param={";
        param = getJsonDataNotEmpty(param,"id",info[0]+"");
        param += "}";
        suixun.ajax(serverUrl+'/roleManager/getCheckedMenu.json',param,"get",function(data){
            suixun.hideLoding(200);//隐藏加载中
            $(".popPhone[data-index=1]").show();
            if(data.code == 200){
                var roles=data.info;
                for(var i=0;i<roles.length;i++){
                    if(roles[i] == null){
                        continue;
                    }
                    var rightid=roles[i].id;
                    if(rightid==null || rightid =="")
                        continue;
                    $(".rightId_box").each(function(i,box) {
                        if(rightid==$(box).attr("data-value"))
                            box.checked=true;
                    });
                }
            }
        });
    },
    /**
     * 关闭修改pop
     */
    onClickHidePop: function () {
        $(".popPhone").hide();
        $(".errorMsg").hide();
        $(".rightId_box").attr('checked',false);

    },
    /**
     * 删除方法
     * @param info
     * @returns {boolean}
     */
    onClickDelete: function (info) {
        if(info==null || info.length<2 || info[0]==null || info[0]==""){
            suixun.alert("参数错误");
            return false;
        }
        var svar = this;
        suixun.confirm_noTit("你确定要删除角色 "+info[1]+" 吗？",function (data) {
            if(data == true){
                suixun.showLoding();//显示加载中
                var id=info[0];
                var param="param={";
                param = getJsonDataNotEmpty(param,"id",id+"");
                param = getJsonDataNotEmpty(param,"status","-1");
                param += "}";
                suixun.ajax(serverUrl+'/roleManager/updateOrAddUser.json',param,"get",function(data){
                    suixun.hideLoding(200);//隐藏加载中
                    if(data!=null && data.info == 200){
                        suixun.alert("删除成功",function (data) {
                            if(data){
                                svar.onClickHidePop();
                                svar.onPageClick(currentpage);
                            }
                        });
                    } else {
                        suixun.alert("删除失败");
                    }
                });
            }
        });
    },
    /**
     * 验证
     * @param e
     */
    onBlurInput: function (e) {
        var classname = e.target.getAttribute("data-error");
        if($(e.target).val() == ''){
            $("."+classname+"").show();
        }else{
            $("."+classname+"").hide();
        }
    },
    render: function () {
        {
            var svar = this;
            var onClickArray = [this.onClickUpdateShow,this.onClickDelete];
            var Tabels = this.state.tableData.map(function (data,index) {
                return (
                    <Table key={data.queryresultid} listNumber={index} queryresultcode={data.queryresultcode} queryresultname={data.queryresultname} queryresultremark={data.queryresultremark} queryresulttype={data.queryresulttype} queryresultstatus={data.queryresultstatus}  queryresulttypeName={data.queryresulttypeName} onClickUpdateShow={onClickArray[0].bind(svar,[data.queryresultid,data.queryresultname,data.queryresultremark,data.queryresultcode,data.queryresulttype])} onClickDelete={onClickArray[1].bind(svar,[data.queryresultid,data.queryresultname])} />
                )
            })
            var Authors = this.state.rightData.map(function (data) {
                return (
                    <Author key={data.id}  name={data.name} id={data.id} child={data.child} />
                )
            })
        }
        return (
            <div className="tableManage-body">
                <form name="tableForm ">
                    <div  className="popPhone popModel" data-index="1">
                        <input type="hidden" name="id" id="id" value=""/>
                        <div className="model"></div>
                        <div className="popModel-info popRight-info">
                            <div className="popModel-title">
                                <span className="popModel-title-content">
                                    <span className="popModel-title-content-solid-left" style={{width:"160px"}}/>
                                    <span className="table-form-title">修改角色信息</span>
                                    <span className="popModel-title-content-solid-right" style={{width:"160px"}}/>
                                </span>
                                <span className="popModel-title-img" onClick={this.onClickHidePop}><img src="../img/icon/close.png" alt="关闭"/></span>
                            </div>
                            <div className="popModel-body">
                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title">角色类型</span>
                                    <span className="popModel-body-input-content" >
                                        <select  name="type" id="type" >
                                            {
                                                typeData.map(function (data,i) {
                                                    return (
                                                        <option value={data.id} >{data.name}</option>
                                                    )
                                                })
                                            }
                                        </select>
                                    </span>
                                    <div className="errorMsg upUserId-error"></div>
                                </div>

                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title">角色名称</span>
                                    <span className="popModel-body-input-content">
                                        <input className="input-content" type="text" name="name" id="name" placeholder="请输入角色名称" onBlur={this.onBlurInput} maxLength="20" data-error="userName-error"/>
                                    </span>
                                    <div className="errorMsg userName-error"></div>
                                </div>
                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title">角色代码</span>
                                    <span className="popModel-body-input-content">
                                        <input className="input-content" type="text" name="code" id="code" placeholder="请输入角色代码" onBlur={this.onBlurInput} maxLength="50" data-error="userId-error" />
                                    </span>
                                    <div className="errorMsg userId-error"></div>
                                </div>
                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title" >备注</span>
                                    <span className="popModel-body-input-content">
                                        <input className="input-content" type="text" name="remark" id="remark" placeholder="请输入备注" onBlur={this.onBlurInput} maxLength="50" data-error="remark-error"/>
                                    </span>
                                    <div className="errorMsg remark-error"></div>
                                </div>
                                <div className="jurisdiction">
                                    <span className="jurisdiction-all">权限 <input type="checkbox" className="allcheck" />全选</span>
                                    <div className="jurisdiction-list">
                                        {Authors}
                                    </div>
                                </div>
                            </div>
                            <div className="popModel-button">
                                <span className="popModel-button-ok" onClick={this.onClockUpdate}>确定</span>
                            </div>
                        </div>
                    </div>
                </form>
                <header>
                    <div className="header-left">
                        <div className="header-left-tableInfo" style={{position:'relative',top:'-16px'}}>角色管理</div>
                        <div className="header-left-annotationsInfo">
                            <img src="../img/icon/annotations.png" />
                            <span className="header-left-annotations-arrowsLeft"/>
                            <div className="header-left-annotations">这里是注释。</div>
                        </div>
                    </div>

                    <div className="header-right">
                        <div className="header-right-select">
                            <div className="school-or-table-user">新增</div>
                        </div>
                    </div>
                </header>
                <div className="tableInfo">
                    <div className="tableInfo-data">
                        <div className="tableInfo-data-table" >
                            <table className="head-body">
                                <thead>
                                    <th style={{width: '6%'}}>序号</th>
                                    <th style={{width: '12%'}}>角色代码</th>
                                    <th style={{width: '12%'}}>角色名称</th>
                                    <th style={{width: '15%'}}>角色类型</th>
                                    <th style={{width: '15%'}}>状态</th>
                                    <th style={{width: '20%'}}>备注</th>
                                    <th style={{width: '20%'}}>操作</th>
                                </thead>
                                <tbody>
                                {this.state.tableData==""?'':Tabels}
                                </tbody>
                            </table>
                            {this.state.tableData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                        </div>
                    </div>
                    <Page maxHeight={this.state.maxHeight} pageLeft={this.state.pageLeft} onPageRight={this.state.onPageRight} currentpage={this.state.currentpage} totlepage={this.state.totlepage} totlerows={this.state.totlerows} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main  otherData={otherData} tableData={tableData} rightData={rightData} />,
    document.getElementById('tableManage')
);

//新增角色
$('.header-right .school-or-table-user').click(function() {
    $("#id").val("");//
    $("#name").val("");//
    $("#remark").val("");//
    $("#code").val("");//
    $("#type").val("");//
    $(".table-form-title").html("新增角色信息");
    $(".popPhone[data-index=1]").show();

});

$(".allcheck").click(function(){
    if($(".allcheck").is(":checked")){
        $(".rightId_box").prop("checked",true);
    }else{
        $(".rightId_box").attr("checked",false);
    }
});
//是否全选
$(".jurisdiction").on('click','.rightId_box',function () {
    var childsCheckBox = $(".jurisdiction-list").children();
    var b = 0;
    for(var i = 0;i<childsCheckBox.length;i++){
        var child = $(childsCheckBox[i]).children();
        if($(child[0]).is(':checked')){
            b ++;
        }
    };
    if(b == childsCheckBox.length){
        $(".allcheck").prop('checked',true);
    }else{
        $('.allcheck').attr('checked',false);
    }
});
//roleParent-box 点击一级菜单
$(".jurisdiction").on('click','.roleParent-box',function () {
    var childClass = $(this).attr("data-value");
    var childsCheckBox = $("."+childClass+"").children();
    if($(this).is(':checked')){
        for(var i = 0;i<childsCheckBox.length;i++){
            $(childsCheckBox[i]).prop('checked',true);
        }
    }else{
        for(var i = 0;i<childsCheckBox.length;i++){
            $(childsCheckBox[i]).attr('checked',false);
        }
    }
});
//roleChild-box 点击二级菜单
//        $(".jurisdiction").on('click','.roleChild-box',function () {
//            var childClass = $(this).attr("data-parentid");//一级菜单id
//            var childsCheckBox = $("."+childClass+"").children();
//            var b = 0;
//            for(var i = 0;i<childsCheckBox.length;i++){
//                if($(childsCheckBox[0]).is(':checked')){
//                    b ++;
//                }
//            };
//            if(b == childsCheckBox.length){
//                $("#"+childClass+"").prop('checked',true);
//            }else{
//                $("#"+childClass+"").attr('checked',false);
//            }
//        });

$(".jurisdiction-list").on('click','.roleParent-val',function () {
    var childClass = $(this).attr("data-value");
    if($("."+childClass+"").is(":hidden")){
        $("."+childClass+"").show();
    }else{
        $("."+childClass+"").hide();
    }
})